package cn.asura.client;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import javax.swing.JTextArea;

/**
 * 1.界面设计
 * 		（1）窗口JFrame
 * 		（2）面板JPanel:testPanel
 * 		（3）两个文本域JTextArea: 显示文本域showText,输入文本域inputText
 */
public class Client extends JFrame{
    private Socket socket;
    private String name;
    private JPanel textPanel;
    private JTextArea showText;
    private JTextArea inputText;

    /*socket,name初始化以及窗口的初始化*/
    public Client(String name) {
        try {
            this.name = name;
            this.setTitle(name);
            socket=new Socket("localhost",8091);
            textPanel=new JPanel();
            showText =new JTextArea(12,42);
            inputText=new JTextArea(4,42);
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*设置窗口具体属性*/
    public void init() {
        this.setSize(500, 310);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setLayout(new BorderLayout());
        this.add(textPanel,BorderLayout.CENTER);

        textPanel.setLayout(new FlowLayout());

        showText.setEditable(false);         //显示文本域不可编辑
        /*添加垂直滚动条*/
        JScrollPane scroll=new JScrollPane(showText);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textPanel.add(scroll);

        inputText.setLineWrap(true);        //输入文本域自动换行
        scroll =new JScrollPane(inputText);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textPanel.add(scroll);

        this.setVisible(true);
    }

    /*向服务器发送信息的方法*/
    public void sendMessage(String message){
        if(message==null||message.trim().length()==0){
            return;
        }
        OutputStream os;
        PrintWriter pw;
        try {
            os =socket.getOutputStream();
            pw=new PrintWriter(new OutputStreamWriter(os),true);
            pw.println(message);
        } catch (Exception ignored) {
        }
    }



    /*在显示文本域中显示服务器发送过来的信息的方法*/
    public void showMessage(){
        try {
            InputStream is=socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String line;
            while((line=br.readLine())!=null){
                showText.append(line+"\r\n");      //显示后自动换行
                showText.setCaretPosition(showText.getText().length());   //实现滚动条随着行数自动滚动
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){
        sendMessage(name);      //连接上服务器立即发送用户名
        KeyAdapter l=new KeyAdapter() {
            public void keyReleased(KeyEvent e){
                if(e.getKeyCode()==KeyEvent.VK_ENTER){
                    String content=inputText.getText().trim();
                    sendMessage(name+":"+content);      //发送格式:  senderName:msg
                    inputText.setText("");      //发送完后清空输入文本域
                }
            }
        };

        inputText.addKeyListener(l);   //将事件绑定到输入文本域上inputText
        inputText.requestFocus();  //获取焦点
        showMessage();    //循环接受服务器返回的数据
    }



    public static void main(String[] args) {
        Client c=new Client("李四");
        c.start();
    }
}